package com.easthotech.contacts.controller;


import com.easthotech.contacts.entity.ExternalProfile;
import com.easthotech.contacts.entity.ExternalTextAttr;
import com.easthotech.contacts.entity.TextAttr;
import com.easthotech.contacts.entity.User;
import com.easthotech.util.HttpUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qq.weixin.mp.aes.AesException;
import com.qq.weixin.mp.aes.WXBizMsgCrypt;
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.FileEntity;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;

/**
 * 联系人
 */
@Controller
public class ContactsController {

    private static final Logger LOGGER = LoggerFactory.getLogger(ContactsController.class);

    /**
     * 创建成员
     * @return
     */
    @RequestMapping("/contacts-create")
    @ResponseBody
    public void create() throws Exception {

        LOGGER.debug("contacts create。。。。");

        User user = new User();
        user.setUserid(UUID.randomUUID().toString());
        user.setName("张三");
        user.setTelephone("13312341234");
        user.setEmail("fkdksks@ww.com");
        user.getDepartment().add(1);
        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(user);

        String access_token =getToken();
        String s2 = HttpUtil.postJson("https://qyapi.weixin.qq.com/cgi-bin/user/create?access_token=" + access_token, s);
        LOGGER.debug("创建成员结果{}",s2);
    }


    /**
     * 获取成员信息
     * @param userid
     * @throws IOException
     */
    @RequestMapping("/contacts-get")
    @ResponseBody
    public void get(String userid) throws IOException {

        HashMap<String, String> map = new HashMap<>();
        map.put("userid","1qaz2wsx");

        map.put("access_token",getToken());

        String s = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/get", map);

        LOGGER.debug("返回信息{}",s);
    }

    /**
     * 更新成员信息
     * @throws Exception
     */
    @RequestMapping("/contacts-update")
    @ResponseBody
    public void update() throws Exception {


        ObjectMapper om = new ObjectMapper();


        User user = new User();

        user.setName("好好学习");
        user.setUserid("1qaz2wsx");


        String s1 = om.writeValueAsString(user);

        String s = HttpUtil.postJson("https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token=" + getToken(), s1);

        LOGGER.debug("返回结果{}",s);


    }


    /**
     * 删除成员
     * @throws IOException
     */
    @RequestMapping("/contacts-delete")
    @ResponseBody
    public void delete() throws IOException {
        HashMap<String, String> map = new HashMap<>();
        map.put("userid","adf70b39-8049-46cb-8d5c-ac2cd261518a");

        map.put("access_token",getToken());

        String s = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/user/delete",map);
    }

    @RequestMapping("/contacts-delete-batch")
    @ResponseBody
    public void deleteBatch() throws Exception {


        HashMap<String, Object> map = new HashMap<>();

        List<String> list = Arrays.asList("wangwu", "ddddd");

        map.put("useridlist",list);


        ObjectMapper om = new ObjectMapper();
        String s = om.writeValueAsString(map);

        String s1 = HttpUtil.postJson("https://qyapi.weixin.qq.com/cgi-bin/user/batchdelete?access_token=" + getToken(), s);

        LOGGER.debug("批量删除结果{}",s1);


    }

    //部门增删改查与员工增删改查基本一致



    //联系人异步批量上传
    @RequestMapping("/upload")
    @ResponseBody
    public void upload() throws IOException, URISyntaxException {

        CloseableHttpClient aDefault = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token="+getToken()+"&type=file");


        InputStream stream = ContactsController.class.getResourceAsStream("/batch_user_sample.csv");

        int available = stream.available();

        LOGGER.debug("available={}",available);

        File file = ResourceUtils.getFile("classpath:batch_user_sample.csv");

        LOGGER.debug("file={}",file.length());

        MultipartEntityBuilder entityBuilder = MultipartEntityBuilder.create();

        HttpEntity media = entityBuilder.addBinaryBody("media", file).build();

        httpPost.setEntity(media);

        LOGGER.debug("executing request {}",httpPost.getRequestLine());

        CloseableHttpResponse execute = aDefault.execute(httpPost);


        HttpEntity entity = execute.getEntity();

        String s = EntityUtils.toString(entity);

        LOGGER.debug("文件上传结果{}",s);

        ObjectMapper om = new ObjectMapper();

        String media_id = om.readTree(s).get("media_id").asText();



        httpPost.setURI(new URI("https://qyapi.weixin.qq.com/cgi-bin/batch/syncuser?access_token="+getToken()));

        HashMap<String, String> map = new HashMap<>();
        map.put("media_id",media_id);


        httpPost.setEntity(new StringEntity(om.writeValueAsString(map),"utf-8"));

        CloseableHttpResponse execute1 = aDefault.execute(httpPost);

        HttpEntity entity1 = execute1.getEntity();

        LOGGER.debug("entity1={}",EntityUtils.toString(entity1));

    aDefault.close();

    }


    //接收通讯录变更事件
    @PostMapping("/receiveMessage")
    @ResponseBody
    public String receiveMessage(String msg_signature, String timestamp, String nonce, @RequestBody String xmlData) throws Exception {
        String sToken = "76v2EBewnoseHqQAEiF63YjQyc8D5U";
        String sCorpID = "ww19ca81efb68ce571";
        String sEncodingAESKey = "niMnqVIB8hNJtpoAkqQU9GIPy9F0XSG84OUiEuU2vVI";

        LOGGER.debug("msg_signature={},timestamp={},nonce={}",msg_signature,timestamp,nonce);

        LOGGER.debug("xmlData={}",xmlData);



        WXBizMsgCrypt wxcpt = new WXBizMsgCrypt(sToken, sEncodingAESKey, sCorpID);


        String sMsg = wxcpt.DecryptMsg(msg_signature, timestamp, nonce, xmlData);


        LOGGER.debug("sMsg={}",sMsg);


        return sMsg;

    }







    public static void main(String[] args) throws IOException {

        InputStream resourceAsStream = ContactsController.class.getResourceAsStream("/batch_user_sample.csv");

        System.out.println(resourceAsStream.available());

    }




    /**
     * 获取通讯录的token
     * @return
     * @throws IOException
     */
    public String getToken() throws IOException {
        HashMap<String, String> map = new HashMap<>();
        ObjectMapper om = new ObjectMapper();
        map.put("corpid","ww19ca81efb68ce571");
        map.put("corpsecret","z-oJXNNqyeVhmX9PZRDHwNbLfxay6_nmqaY4LVdVMvs");

        String s1 = HttpUtil.get("https://qyapi.weixin.qq.com/cgi-bin/gettoken", map);
        LOGGER.debug("获取token结果{}",s1);
        String access_token = om.readTree(s1).get("access_token").asText();
        LOGGER.debug("access_token",access_token);

        return access_token;
    }



    @RequestMapping("/test")
    @ResponseBody
    public void test() throws IOException {

        HashMap<String, String> map = new HashMap<>();
        map.put("name","哈哈哈");
        map.put("userid","1qaz2wsx");

        ObjectMapper mapper = new ObjectMapper();
        String s1 = mapper.writeValueAsString(map);

        LOGGER.debug("s1={}",s1);

        StringEntity entity = new StringEntity(s1,"utf-8");
        entity.setContentType("application/json");
        CloseableHttpClient client = HttpClients.createDefault();

        HttpPost httpPost = new HttpPost("https://qyapi.weixin.qq.com/cgi-bin/user/update?access_token="+getToken());

        httpPost.setEntity(entity);

        CloseableHttpResponse execute = client.execute(httpPost);

        LOGGER.debug("发送请求{}",httpPost.getRequestLine());
        LOGGER.debug("请求参数{}",EntityUtils.toString(httpPost.getEntity()));

        String s = EntityUtils.toString(execute.getEntity());

        LOGGER.debug("返回结果{}",s);



    }


@RequestMapping("/testpara")
@ResponseBody
    public void testPara(String name,String userid){

        LOGGER.debug("userid={}",userid);
    }


}
